package com.beney.message;

import com.alibaba.fastjson.JSON;
import com.beney.codec.MessagePacket;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 实现和 SpringMVC 中 DispatchServlet 类似的功能，
 * 将接收到的 protocol 分发到对应的 MessageHandler 中进行处理
 * <p>
 * <p>
 * MessageDispather ----> MessageHandlerA
 * \--> MessgeeHanderlB
 * \ -> MessageHandlerC
 * \...
 */
@ChannelHandler.Sharable
public class MessageDispatcher extends SimpleChannelInboundHandler<MessagePacket> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MessageHandlerContainer handlerContainer;

    // TODO: 工作线程数 参数考量
    private final ExecutorService executors
            = Executors.newFixedThreadPool(2 * Runtime.getRuntime().availableProcessors());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessagePacket messagePacket) throws Exception {
        // 解析出 msgPacket 具体的内容 message 的类型
        MessageHandler handler = handlerContainer.getMessageHandler(messagePacket.getType());
        Class<? extends Message> msgClass = handlerContainer.getMessageClass(handler);
        Message message = JSON.parseObject(messagePacket.getMessage(), msgClass);

        executors.submit(() -> handler.handle(ctx.channel(), message));
    }
}
